package com.ebai.product.management.base.controller;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public abstract class WebController {

    protected final Logger logger = Logger.getLogger(this.getClass());

    public static final String CONTENTTYPE_HTML = "text/html";

    public static final String CONTENTTYPE_JSON = "text/json";

    public static final String CONTENTTYPE_XML = "text/xml";

    public static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 直接通过<b>{@link HttpServletResponse}写数据到客户端</b>,可以指定编码,文件类型
     * @param response {@link HttpServletResponse}
     * @param contentType 文件类型
     * @param s 数据
     */
    public void sendDirectToClient(HttpServletResponse response, String contentType, String s) {
        StringBuffer sbContentHead = new StringBuffer();
        sbContentHead.append(contentType)
                .append(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)
                .append(DEFAULT_CHARSET);
        response.setContentType(sbContentHead.toString());
        try {
            PrintWriter writer = response.getWriter();
            writer.write(s);
            writer.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
